<template>
  <!-- 群聊显示面板 -->
  <div class="chat-container">
    <!-- 工具栏 -->
    <!-- <div class="actionbar elevation-1">
      <div class="left"></div>
      <div class="title">{{ title }}</div>
      <div class="right"></div>
    </div>-->
    <!-- 加群 -->
    <div class="search-bar">
      <div class="search-title">超级群聊</div>
      <div class="search" @click="showSearchBox = true">
        <img src="@/assets/icons/search_chat.svg" alt class="plus-icon" />
      </div>
      <div class="add" @click="showPopup = true">
        <img src="@/assets/icons/plus.svg" alt class="plus-icon" />
      </div>
      <!-- 弹出层菜单 -->
      <div class="popup-menu-wrapper" @click="showPopup = false" v-show="showPopup">
        <div class="popup-menu">
          <ul class="menu-list">
            <li class="list-item" @click.stop="onAddGroup">
              <div class="icon flex-center">
                <img src="@/assets/images/group_white.png" alt />
              </div>
              <div class="title flex-center">
                <span>新建群聊</span>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <!-- 搜索框 -->
    <!-- <div class="search-bar">
      <div class="title">超级社群</div>
      <div class="input-wrapper">
        <div class="place-holder flex-center"></div>
        <cube-input v-model="searchGroupId" class="search-input" type="number"></cube-input>
      </div>
      <div class="action flex-center" @click="onSearch">
        <div class="search-button">搜索</div>
      </div>
    </div>-->
    <!-- 搜索结果 -->
    <!-- <div class="search-box" v-if="searchResult !== null"> -->
    <!-- <li
          v-for="(item, i) of searchResult"
          class="list-item"
          :key="i"
          v-hammer:tap="(ev) => onSearchClicked(ev, item)"
    >-->
    <!-- <group-list-item :group="searchResult"></group-list-item> -->

    <!-- <div class="group-list-item">
        <div class="icon">
          <img :src="searchResult.headUrl" alt />
        </div>
        <div class="info">
          <div class="title">{{ searchResult.groupNick }}</div>
        </div>
        <div class="desc" v-hammer:tap="(ev) => onSearchClicked(ev)">
          <div class="time">加入</div>
        </div>
      </div>

    <div class="cancel-search" @click="searchResult = null"></div>-->
    <!-- </li> -->
    <!-- </div> -->

    <!-- 置顶卡片列表 -->
    <div class="fixed-card"></div>

    <div class="group-list-wrapper">
      <cube-scroll
        ref="scroll"
        :data="storeGroupList"
        :options="options"
        @pulling-down="onPullingDown"
        :scroll-events="['scroll']"
      >
        <ul class="group-list">
          <li
            class="list-item"
            v-hammer:tap="(ev) => { $router.push({name: 'Notification'}) }"
            key="-1"
          >
            <group-list-item :group="notify"></group-list-item>
          </li>
          <li
            v-for="(item, i) in storeGroupList"
            class="list-item"
            :key="i"
            v-hammer:tap="(ev) => onGroupClicked(ev, item)"
            v-hammer:press="(ev) => onGroupPressed(ev, item)"
          >
            <group-list-item :key="i" :group="item"></group-list-item>
          </li>
        </ul>
      </cube-scroll>
    </div>

    <add-group
      @hide="showAddGroup = false"
      class="add-group-wrapper"
      :class="{'show': showAddGroup}"
    />

    <search-box
      @hide="showSearchBox = false"
      :searchResult="searchResult"
      class="add-group-wrapper"
      :class="{'show': showSearchBox}"
    />
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { Action, Mutation, Getter, namespace } from "vuex-class";
import { Webim } from "@/utils/types";
import { Response } from "@/api/bean";
import { DIALOGUE, ImClient, MsgTypeKV } from "@/api/socket/imClient";
import { convertListTime, getTimeString } from "@/utils/common";
import MessageMixin from "@/mixins";
import { map } from 'lodash';
declare const $Vue: Vue;
declare const webim: Webim;
declare const getPrePageGroupHistroyMsgInfoMap: any;
const chatModule = namespace("chatModule");
const userModule = namespace("userModule");

@Component<Chat>({
  mixins: [MessageMixin]
})
export default class Chat extends Vue {

  @userModule.State("loginInfo") loginInfo: any;
  @userModule.State("selToID") selToID: any;
  @userModule.State("selType") selType: any;
  @userModule.State("selSess") selSess: any;

  @userModule.Action("saveSelSessFN") saveSelSessFN: any;
  @userModule.Action("saveSelToIDFN") saveSelToIDFN: any;
  // 存在全局的 每次先读取它 然后从服务端更新
  @chatModule.State("storeGroupList") storeGroupList: any;

  @chatModule.State("currentGroup") currentGroup: any;
  @chatModule.State("wxShareData") wxShareData: any;
  @chatModule.Action("saveGroupListFN") saveGroupListFN: any;
  @chatModule.Mutation("saveGroupList") saveGroupList: any;
  @chatModule.Action("saveCurrentGroupFN") saveCurrentGroupFN: any;

  private title: string = "首页";

  private notify: any = {
    groupNick: '系统通知',
    headUrl: 'https://c-c-a.jiahuagame.com/source/icon/pj/icon.png',
    groupId: -1,
  }

  private size: number = 50;
  private offset: number = 100;

  // 搜索文本
  private searchGroupId: string = "";

  private searchResult: any = {};

  private groupList: any = [];

  private options: any = {
    pullDownRefresh: {
      txt: '刷新中...',
    },
  };

  private showSearchBox: boolean = false;

  private showAddGroup: boolean = false;
  // 弹出层菜单
  private showPopup: boolean = false;

  private eventList: Array<string> = [
    "onWebimLogined",
    "onMsgNotify",
    "$createGroup",
    "$getGroupList",
    "$searchGroupByGroupId",
    "$applyGroup",
    // "$getWxShare",
  ];

  private get sortedGroupList() {
    return this.storeGroupList.sort((a, b) => {
      return b.lastTime - a.lastTime
    });
  }

  private get getStoreGroupList() {
    return this.storeGroupList;
  }

  private sortList(list: Array<any>): Array<any> {
    return list.sort((a, b) => {
      return b.lastTime - a.lastTime
    });
  }
  private listGot: boolean = true;
  private interval: any = null;

  protected mounted() {
    this.initEvents(this.eventList);
    document.title = ' ';

    // this.groupList = this.storeGroupList.slice();
    // this.getGroupUnread();
    // 取全局备份

    this.interval = setInterval(() => {
      if (this.listGot) {
        this.listGot = false;
        this.sendMessage(MsgTypeKV.getGroupList, {
          signUrl: window.location.href
        });
        clearInterval(this.interval);
        this.interval = null;
      }
    }, 1000);

  }


  /**
   * 登录后才进行操作
   */
  private onWebimLogined() {
    if (this.listGot) {
      this.listGot = false;
      this.sendMessage(MsgTypeKV.getGroupList, {
        signUrl: window.location.href
      });
    }
  }

  /**
   * 消息提醒 发送新消息后将消息放入对应的队列
   */
  private onMsgNotify(data) {

    this.getGroupMessages();

    // let groupList = this.storeGroupList.slice();
    // // 遍历消息列表
    // data.forEach((msg: any) => {
    //   groupList.forEach((item: any, i: any) => {
    //     if (msg.sess._impl.id === item.imGroupId) {
    //       let msgList = msg.sess.msgs();

    //       let list: Array<any> = [];
    //       msgList.forEach((item: any) => {
    //         list.push({
    //           elems: item.elems,
    //           extraInfo: item.extraInfo,
    //           fromAccount: item.fromAccount,
    //           fromAccountHeadurl: item.fromAccountHeadurl,
    //           fromAccountNick: item.fromAccountNick,
    //           isSend: item.isSend,
    //           seq: item.seq,
    //           subType: item.subType,
    //           time: item.time,
    //           uniqueId: item.uniqueId,
    //           LastMsg: {},
    //         });
    //       });
    //       // 最后一条消息不取系统消息
    //       let last = list.length - 1;
    //       if (last <= 0) {
    //         last = 0
    //       } else {
    //         while (list[last].subType === webim.GROUP_MSG_SUB_TYPE.TIP) {
    //           last--;
    //         }
    //       }

    //       // this.$set(this.groupList[i], 'msgList', list);

    //       groupList[i].msgList = list
    //       // this.$set(
    //       //   this.groupList[i],
    //       //   "LastMsgTime",
    //       //   getTimeString(list[last].time, false)
    //       // );
    //       groupList[i].LastMsgTime = getTimeString(list[last].time, false);
    //       let time = list[last].time;
    //       if (!time) {
    //         time = 0;
    //       }
    //       if (groupList[i].isTop) {
    //         time = (new Date().getTime()) + 10000 * i;
    //       }
    //       if (time.toString().length <= 10) {
    //         time = time * 1000;
    //       }
    //       // this.$set(
    //       //   this.groupList[i],
    //       //   "lastTime",
    //       //   time,
    //       // );
    //       groupList[i].lastTime = time
    //       // this.$set(this.groupList[i], 'LastMsg', list[last]);
    //       groupList[i].LastMsg = list[last];

    //       console.error("CXHHHHHAAAT ,onMsgNotify", msg);
    //     }
    //   });
    // });

  }

  /**
   * 新建群聊
   */
  private onAddGroup() {
    this.showAddGroup = true;
    this.showPopup = false;
  }

  /**
   * 根据群号搜索群信息
   */
  private onSearch() {
    // this.getGroupMessages();
    if (this.searchGroupId === "") {
      return this.$createToast({
        txt: "请输入群聊ID",
        type: "warn",
        time: 3000,
      }).show();
    }
    // this.sendMessage(MsgTypeKV.searchGroupByGroupId, {
    //   groupId: this.searchGroupId
    // });
  }

  /**
   * 点击搜索结果 加入群聊
   */
  private onSearchClicked(ev, item) {
    this.sendMessage(MsgTypeKV.applyGroup, {
      groupId: this.searchResult.groupId
    });
  }

  private onGroupClicked(ev: any, item: any) {
    this.saveCurrentGroupFN(item);
    this.$router.push({
      name: "ChatPanel",
      params: item,
    });
  }

  /**
   * 长按事件
   */
  private onGroupPressed(ev: any, item: any) {
    // this.$createActionSheet({
    //   // title: '',
    //   data: [
    //     {
    //       content: "",
    //       class: "cube-foo"
    //     },
    //     {
    //       content: "置顶",
    //       align: "left"
    //     }
    //   ],
    //   onSelect: (item, index) => { }
    // }).show();
  }

  private onPullingDown() {
    this.sendMessage(MsgTypeKV.getGroupList, {
      signUrl: window.location.href
    });
  }

  private onPullingUp() { }

  /**
   * 微信签名
   */
  private wxShare(data: any) {
    // this.saveWxShareDataFN(data);
    // 自定义“分享给朋友”及“分享到QQ”按钮的分享内容
    wx.updateAppMessageShareData({
      title: "超级社群", // 分享标题
      desc: "", // 分享描述
      link: this.wxShareData.shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: this.wxShareData.shareLink, // 分享图标
      success: function () {
        // 设置成功
      }
    });
    // 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容
    wx.updateTimelineShareData({
      title: "超级社群", // 分享标题
      link: this.wxShareData.shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: this.wxShareData.shareLink, // 分享图标
      success: function () {
        // 设置成功
      }
    });
  }

  /**
   * 计数
   */
  private listCount: number = 0;

  /**
   * 删除session, 否则无法再次同步信息
   */
  private deleteSessions() {
    let sessMap = webim.MsgStore.sessMap();
    for (let key in sessMap) {
      webim.MsgStore.delSessByTypeId(this.selType, key.replace(this.selType, ''));
    }
  }

  /**
   * 从群列表中获取群会话信息
   */
  private getGroupMessages() {
    this.groupList = [];
    this.listCount = 0;

    this.deleteSessions();

    this.storeGroupList.forEach((item: any, i: number) => {
      this.groupList[i] = Object.assign({}, item);

      // 获取群详细资料
      this.getGroupInfo(
        item.imGroupId,
        resp => {
          this.listCount++;
          let options = {
            GroupId: item.imGroupId,
            ReqMsgSeq: resp.GroupInfo[0].NextMsgSeq - 1,
            ReqMsgNumber: 10,
          };
          if (
            options.ReqMsgSeq == null ||
            options.ReqMsgSeq == undefined ||
            options.ReqMsgSeq <= 0
          ) {
            webim.Log.warn(
              "该群还没有历史消息:options=" + JSON.stringify(options)
            );
            if (this.listCount === (this.storeGroupList.length)) {
              // this.$store.commit(chatModule/'saveGroupList', this.sortList(this.groupList));
              setTimeout(() => {
                this.$store.commit('chatModule/saveGroupList', this.sortList(this.groupList));
              }, 800)
            }
            return;
          }

          // this.saveSelSessFN(null);
          // webim.MsgStore.delSessByTypeId(this.selType, this.selToID);

          webim.syncGroupMsgs(
            options,
            msgList => {
              if (msgList.length == 0) {
                webim.Log.warn(
                  "该群没有历史消息了:options=" + JSON.stringify(options)
                );
                if (this.listCount === (this.storeGroupList.length)) {
                  this.$store.commit('chatModule/saveGroupList', this.sortList(this.groupList));
                }
                return;
              }
              // 成功
              let list: Array<any> = [];
              msgList.forEach((subItem: any) => {
                list.push({
                  elems: subItem.elems,
                  extraInfo: subItem.extraInfo,
                  fromAccount: subItem.fromAccount,
                  fromAccountHeadurl: subItem.fromAccountHeadurl,
                  fromAccountNick: subItem.fromAccountNick,
                  isSend: subItem.isSend,
                  seq: subItem.seq,
                  subType: subItem.subType,
                  time: subItem.time,
                  uniqueId: subItem.uniqueId,
                  LastMsg: {},
                });
              });
              this.groupList[i].msgList = list;
              if (list.length > 0) {
                // 最后一条消息不取系统消息
                let last = list.length - 1;
                if (last <= 0) {
                  last = 0
                } else {
                  let msgType = list[last].elems[0].type;
                  let contentType = ''
                  if (msgType == "TIMCustomElem") {
                    contentType = list[last].elems[0].content.desc;
                  }
                  while (list[last].subType === webim.GROUP_MSG_SUB_TYPE.TIP && contentType == 'message-tip') {
                    last--;
                  }
                }
                this.groupList[i].LastMsgTime = getTimeString(list[last].time, false);

                // this.$set(this.groupList[i], 'msgList', list);
                // this.$set(
                //   this.groupList[i],
                //   "LastMsgTime",
                //   getTimeString(list[last].time, false)
                // );
                let time = list[last].time;
                if (list.length === 0) {
                  time = 0;
                }
                if (this.groupList[i].isTop) {
                  time = (new Date().getTime()) + 10000 * i + time;
                }
                this.groupList[i].lastTime = time;
                this.groupList[i].LastMsg = list[last];
                // this.$set(
                //   this.groupList[i],
                //   "lastTime",
                //   time,
                // );
                // this.$set(this.groupList[i], 'LastMsg', list[last]);
              }
              let msgSeq = msgList[0].seq - 1;
              // console.error('groupListgroupList', this.storeGroupList.length, i);

              if (this.listCount === (this.storeGroupList.length)) {
                setTimeout(() => {
                  this.$store.commit('chatModule/saveGroupList', this.sortList(this.groupList));
                }, 800)
              }
              // console.warn("同步群聊信息", msgList);
            },
            err => {
              this.listCount++;
              if (this.listCount === (this.storeGroupList.length)) {
                setTimeout(() => {
                  this.$store.commit('chatModule/saveGroupList', this.sortList(this.groupList));
                }, 800)
              }
            }
          );
        },
        (err) => {
          this.listCount++;
          if (this.listCount === (this.storeGroupList.length)) {
            setTimeout(() => {
              this.$store.commit('chatModule/saveGroupList', this.sortList(this.groupList));
            }, 800)
          }
        }
      );
    });
  }

  /**
   * 获取消息未读计数
   */
  // private getGroupUnread() {
  //   // 存到永久存储里去
  //   let UnreadMap: any = {};

  //   let localUnreadMap: any = localStorage.getItem('UnreadMap');

  //   if (localUnreadMap) {
  //     localUnreadMap = JSON.parse(localUnreadMap);
  //   } else {
  //     localUnreadMap = {};
  //   }

  //   this.groupList.forEach((item: any, i: number) => {
  //     let skey = "GROUP" + item.imGroupId;
  //     let sessMap = webim.MsgStore.sessMap();
  //     let map = sessMap[skey];
  //     let localUnread: number = Number(localUnreadMap[skey]);
  //     if (map) {
  //       let unread: any = map.unread() - localUnread;
  //       if (unread > 99) {
  //         unread = '99+';
  //       }
  //       this.$set(this.groupList[i], 'unread', unread);
  //       UnreadMap[skey] = unread;
  //     } else {
  //       this.$set(this.groupList[i], 'unread', 0);
  //       UnreadMap[skey] = 0;
  //     }
  //     localStorage.setItem('UnreadMap', JSON.stringify(UnreadMap));
  //   });
  //   this.saveGroupListFN(this.groupList);
  // }

  /**
   * 更新最近会话的未读消息数
   */
  private updateGroupUnread() {

  }

  /**
   * 获取群资料
   */
  private getGroupInfo(group_id_list: string, cbOK: Function, cbErr: Function) {
    let options = {
      GroupIdList: [group_id_list],
      GroupBaseInfoFilter: [
        "Type",
        "Name",
        "Introduction",
        "Notification",
        "FaceUrl",
        "CreateTime",
        "Owner_Account",
        "LastInfoTime",
        "LastMsgTime",
        "NextMsgSeq",
        "MemberNum",
        "MaxMemberNum",
        "ApplyJoinOption",
        "ShutUpAllMember"
      ],
      MemberInfoFilter: [
        "Account",
        "Role",
        "JoinTime",
        "LastSendMsgTime",
        "ShutUpUntil"
      ]
    };
    webim.getGroupInfo(
      options,
      (resp) => {
        if (cbOK) {
          cbOK(resp);
        }
      },
      (err) => {
        cbErr(err);
        // this.$createToast({
        //   txt: err.ErrorInfo,
        //   type: "warn",
        //   time: 3000
        // }).show();
      }
    );
  }


  /**
   * 返回的建群的结果
   */
  private $createGroup(data: Response<any>) {
    this.showAddGroup = false;
    if (data.result === 0) {
      this.$createToast({
        txt: data.message,
        type: "correct",
        time: 3000
      }).show();

      this.sendMessage(MsgTypeKV.getGroupList, {
        signUrl: window.location.href
      });
    } else {
      this.$createToast({
        txt: data.message,
        type: "warn",
        time: 3000
      }).show();
    }
  }

  /**
   * 获取群列表
   */
  private $getGroupList(data: any) {
    this.showAddGroup = false;
    if (data.result === 0) {

      let newGroupList: Array<any> = data.groupList.slice();
      newGroupList.forEach((item: any, i: number) => {
        this.storeGroupList.forEach((subItem: any, j: number) => {
          if (item.groupId === subItem.groupId) {
            item.msgList = subItem.msgList;
            item.LastMsg = subItem.LastMsg;
            item.LastMsgTime = subItem.LastMsgTime;
            item.lastTime = subItem.lastTime;
          }
        });
      });

      this.saveGroupListFN(this.sortList(newGroupList));
      this.getGroupMessages();
    }
  }

  /**
   * 根据群ID搜索群
   */
  private $searchGroupByGroupId(data: any) {
    if (data.result === 0) {
      this.searchResult = {
        ...data.info,
        imGroupId: data.imGroupId
      };
      this.showSearchBox = true;
    } else {
      this.searchResult = {};
    }
  }

  /**
   * 申请加入群之后的返回结果处理
   */
  private $applyGroup(data: Response<any>) {
    this.showSearchBox = false;
    this.showAddGroup = false;
    this.searchResult = false;
    this.sendMessage(MsgTypeKV.getGroupList, {
      signUrl: window.location.href
    });
    if (data.result === 0) {
      this.$createToast({
        txt: data.message,
        type: "correct",
        time: 3000
      }).show();
    } else {
      this.$createToast({
        txt: data.message,
        type: "warn",
        time: 3000
      }).show();
    }
  }

  /**
   * 获取微信分享
   */
  private $getWxShare(data: any) {
    if (data.result === 0) {
      // window['wxShareData'] = data;
    } else {
      this.$createToast({
        txt: data.message,
        type: "warn",
        time: 3000
      }).show();
    }
  }
}
</script>

<style lang="stylus" scoped>

.chat-container
  width 100%
  height 100%
  overflow-x hidden
  overflow-y auto
  position relative
  &.no-actionbar
    padding-top 0
  .actionbar
    height 40px
    width 100%
    position fixed
    top 0
    left 0
    background-color #fcfcfc
    display flex
    align-items center
    justify-content space-between
    z-index 999
    .left,
    .right
      align-items center
      justify-content center
      display flex
      width 3rem
      height 100%
      img
        width 16px
        height 16px
    .title
      font-size 18px
  .search-bar
    display flex
    justify-content space-between
    align-items center
    height 42px
    border-bottom 0.8px solid #b9b9b9
    .add 
      position absolute
      right 10px
      top 8px
    .search 
      position absolute
      right 56px
      top 8px
    .title
      flex-basis 15%
      font-size 12px
      color #898989
    .input-wrapper
      flex-basis 70%
      position relative
      .place-holder
        position absolute
        width 100px
        height 24px
        color #909090
        font-size 14px
    .action
      flex-basis 15%
      .search-button
        width 80%
        height 24px
        line-height 24px
        font-size 14px
        background #27bf64
        color white
        border-radius 2px
  .search-box
    position absolute
    width 100%
    height calc(100% - 70px)
    left 0
    top 70px
    background white
    z-index 10
  .cancel-search
    width 100%
    height 100%


  .group-list-wrapper
    position fixed
    top 42px
    left 0
    bottom 48px
    width 100%
    border-top 0.6px solid #dadada
    .group-list
      .list-item
        display flex
        justify-content space-between
        align-items center
        background #fff
        &.top
          background #ddd
        .icon 
          flex-basis 20%
          width 20%
          height 100%
          position relative
          img
            width 40px
            height 40px
            border-radius 8px
          .count
            width 17px
            height 17px
            border-radius 50%
            background-color #f44336
            position absolute
            top 0
            right 0
            color white
            font-size 11px
            line-height 16px
        .info
          flex-basis 70%
          width 70%
        .desc
          flex-basis 10%
          width 10%
.add-group-wrapper
  width 100% 
  height 100%
  position absolute
  top 2000px
  left 0
  opacity 0
  transition opacity 0.5s 0s ease
  &.show 
    top 0
    opacity 1

.time
  border-radius 16px
  border 1px solid rgb(87, 189, 109)
  color rgb(87, 189, 109)
  font-size 12px
  padding 2px 4px

.plus-icon
  width 22px
  height 22px

.popup-menu-wrapper
  width 100%
  height 100%
  position fixed
  top 0
  left 0
  z-index 10
  transition all 1s 0s ease
  &:before
    content ""
    border-style solid
    border-width 0 10px 10px 0
    border-color transparent #4d4d4d transparent transparent
    position absolute
    top 38px
    right 16px
    transform rotateZ(-45deg)
  .popup-menu
    width 160px
    background #4d4d4d
    position absolute
    border-radius 3px
    top 42px
    right 4px
    padding 4px 10px
    box-sizing border-box
    z-index 10
    transition all 1s 0s ease
    .menu-list
      display flex 
      .list-item
        width 80%
        height 32px
        display flex
        align-items center
        padding 3px 6px
        .icon 
          flex-basis 30%
          width 30%
          height 100%
          img 
            width 20px
            height 18px
        .title
          flex-basis 70%
          width 70%
          color white
          font-size 16px
          height 100%

.search-title
  padding-left 12px

</style>

